//
//  AddFamilyViewController.m
//  安好
//
//  Created by lianchuang on 14-11-13.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import <AssetsLibrary/AssetsLibrary.h>
#import "MainViewController.h"

#import "AddFamilyViewController.h"
#import "AFNetworking.h"
#import "WriteFamilyViewController.h"
#import "CheckNumberClass.h"
#import "ShowMyFamilyDetialViewController.h"

#import "UIImageView+MJWebCache.h"
#import "SDImageCache.h"

#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

#define CellLineColor [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1]

@interface AddFamilyViewController ()<UITableViewDataSource,UITableViewDelegate,WriteFamilyViewControllerDelegate,UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate>

/**
 *  选好图片之后把图片得到
 */
@property(nonatomic,strong)UIImage * familyHeaderImg;
/**
 *  半透明的图片 -- 当点击升起pickerView的时候 这个也sheng起来
 */
@property(nonatomic,strong)UIView * alphaView;
@end

@implementation AddFamilyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeNavBar];
    [self loadData];
    [self makeTableView];
    
    
    //“关系”
    [self makeRelationShipPickerView];
    //出生年月
    [self makeBirthdayPickerView];
}
/**
 *  设置导航条
 */
-(void)makeNavBar
{
    self.navigationItem.title = @"添加家人";
    // 返回按钮图片
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    UIBarButtonItem *OkBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(FinishAndUploadingData)];
    OkBtnImg.tintColor = [UIColor whiteColor];
    OkBtnImg.tag = 100;
    self.navigationItem.rightBarButtonItem = OkBtnImg;
}
/**
 *  返回--“用药提醒”
 */
-(void)backBtnClicked
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - "完成"上传数据
/**
 *  "完成"--上传数据--去展示页面
 */
-(void)FinishAndUploadingData
{
    [self recoverPickerViewAndTableViewFrame];
    
    [self AFNetRequestForFamilyHeaderImgAndFamilyDetial];
    
}

#pragma mark - 上传家人头像和参数
-(void)AFNetRequestForFamilyHeaderImgAndFamilyDetial
{
    //对各个参数进行判断
    if ([[self.paratorDic objectForKey:@"realname"] length] ==0)
    {
        [self showCustomHudSingleLine:@"真实姓名不可为空"];
        return ;
    }else if ([[self.paratorDic objectForKey:@"realname"] length] ==1){
        [self showCustomHudSingleLine:@"姓名长度不能为1位"];
        return;
    }
    else if ([[self.paratorDic objectForKey:@"realname"] length] > 10)
    {
        [self showCustomHudSingleLine:@"姓名长度不可大于10位"];
        return;
    }
    
    if ([[self.paratorDic objectForKey:@"username"] length] > 6)
    {
        [self showCustomHudSingleLine:@"昵称字数不可大于6位"];
        return ;
    }else if([[self.paratorDic objectForKey:@"username"] length] == 0)
    {
        [self showCustomHudSingleLine:@"昵称不能为空"];
        return ;
    }
    if ([[self.paratorDic objectForKey:@"type"]length] == 0)
    {
        [self showCustomHudSingleLine:@"请选择关系"];
        return ;
    }
    if ([[self.paratorDic objectForKey:@"mobile"] length] != 0 )
    {
        if([CheckNumberClass checkPhoneNumber:[self.paratorDic objectForKey:@"mobile"]]==NO)
        {
            return ;
        }
        
    }
    NSInteger IdcardLength = [[self.paratorDic objectForKey:@"idcard"] length];
    if (IdcardLength != 0 ) {
        if (IdcardLength == 18 || IdcardLength == 15) {
            
        }else
        {
            [self showCustomHudSingleLine:@"请输入正确的身份证号"];
            return ;
        }
    }
    
    //参数合法后--才开始网络请求
    [self showActionView];
    NSString *postURL = [NSString stringWithFormat:@"%@user/addhome/",kBaseURL];
    [self.paratorDic setValue:kPlatform forKey:@"platform"];
    [self.paratorDic setValue:kVersion forKey:@"version"];
    MyNSLog("-------%@", self.paratorDic);
    NSData * imageData = UIImageJPEGRepresentation(self.familyHeaderImg, 0.5);
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:postURL parameters:self.paratorDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //判断是否选好了图片，如果没选就不走这个
        if (imageData) {
            [formData appendPartWithFileData:imageData name:@"file" fileName:@"familyHeaderImg.jpg" mimeType:@"image/jpeg"];
        }
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
 
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        [self hiddenActionView];
        if (error)
        {
            MyNSLog("Error: %@", error);
            [self showCustomHudSingleLine:@"添加失败失败"];
        }
        else
        {
            //网络连接成功
            [self hiddenActionView];
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"0"])
            {
                MyNSLog("上传失败");
                MyNSLog("家人头像上传 %@", responseObject[@"msg"]);
                [self showCustomHudSingleLine:responseObject[@"msg"]];
            }
            else
            {
                MyNSLog("成功");
                //获取家人fid
                NSDictionary * dic = responseObject[@"data"];
                NSString * fid = dic[@"fid"];
                NSString * avatar = dic[@"avatar"];
                MyNSLog("%@", fid);
                //获取用户uid
                UserModel * model =[[UserManager shareInstance]getUserInfo];
                NSString * uid = model.uid;
                //
                
                [self.paratorDic setValue:avatar forKey:@"avatar"];
                [self.paratorDic setValue:uid forKey:@"uid"];
                [self.paratorDic setValue:fid forKey:@"fid"];
                
                //判断选填的内容是否为空，为空则给其附一个空的字符串
                if (self.paratorDic[@"gender"] == nil) {
                    [self.paratorDic setValue:@"0" forKey:@"gender"];
                }
                if (self.paratorDic[@"birthday"] == nil) {
                    [self.paratorDic setValue:@"" forKey:@"birthday"];
                }
                if (self.paratorDic[@"idcard"] == nil) {
                    [self.paratorDic setValue:@"" forKey:@"idcard"];
                }
                if (self.paratorDic[@"mobile"] == nil) {
                    [self.paratorDic setValue:@"" forKey:@"mobile"];
                }
                
                //判断是否有图，添加上图就把图保存本地
                if (imageData) {
                    //本地文件夹路径
                    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                    //文件夹地址
                    NSString * headerImgFloder = [docPath stringByAppendingString:[NSString stringWithFormat:@"/FamilyHeaderFloder/"]];
                    //图片地址
                    NSString * newPicPath = [headerImgFloder stringByAppendingString:[NSString stringWithFormat:@"headerImg%@%@.jpg",uid,fid]];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    
                    //如果这个文件夹存并且这个图片存在就进行下一步操作--这是新添加的家人图片不是编辑，所以这一步是不会发生的
                    if ([fileManager fileExistsAtPath:headerImgFloder] && [fileManager fileExistsAtPath:newPicPath]) {
                        //把图片更新
                        [UIImageJPEGRepresentation(self.familyHeaderImg, 0.5) writeToFile:newPicPath atomically:YES];
                        
                    }
                    //如果这个文件夹不存在
                    else{
                        //文件夹不存在，先创建文件夹
                        if (![fileManager fileExistsAtPath:headerImgFloder]) {
                            [[NSFileManager defaultManager] createDirectoryAtPath:headerImgFloder withIntermediateDirectories:YES attributes:nil error:nil];
                            //同时要把创建这个文件夹的时间保存下来
                        
                            NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
                            //先判断是否已经有了保存文件的时间
                            NSDate * oldTime = [timeUser objectForKey:@"FamilyHeaderFloderDate"];
                            NSDate * nowDate = [NSDate date];
                            //如果没有那么就把此时的时间保存下来
                            if (oldTime == nil) {
                                [timeUser setObject:nowDate forKey:@"FamilyHeaderFloderDate"];
                                [timeUser synchronize];
                            }
                        }
                        //再添加图片
                        [UIImageJPEGRepresentation(self.familyHeaderImg, 0.5) writeToFile:newPicPath atomically:YES];
                    }
                }
                
                ShowMyFamilyDetialViewController * showDetial = [[ShowMyFamilyDetialViewController alloc] init];
                //把家人信息不管是否添加值，没有添加就赋值@“”，传给下一个页面
                showDetial.familyAllDetialDic = self.paratorDic;
                
                [self.navigationController pushViewController:showDetial animated:YES];
                
            }
        }
    }];
    [uploadTask resume];

}

#pragma mark - 加载数据
-(void)loadData
{
    self.paratorDic = [NSMutableDictionary dictionaryWithCapacity:0];
    self.placeholderDic = [NSMutableDictionary dictionaryWithCapacity:0];
    self.tempDic = [NSMutableDictionary dictionaryWithCapacity:0];
    //必填内容
    NSArray *requiredRemiderArray = @[@"真实姓名",@"关       系",@"昵       称"];
    NSArray *requiredKeys = @[@"realname",@"type",@"username"];
    //选填内容-1
    NSArray *optionRemindFirstArray = @[@"性       别",@"出生年月"];
    NSArray *optionRemindFirstKeys = @[@"gender",@"birthday"];
    //选填内容-2
    NSArray *optionReminderSecondArray = @[@"手  机  号",@"身  份  证"];
    NSArray *optionSecondkeys = @[@"mobile",@"idcard"];
    /**
     *  数据--保存提示的3个数组，
     */
    self.takeDrugDataArray = @[requiredRemiderArray,optionRemindFirstArray,optionReminderSecondArray];
    
    NSArray * requiredPlaceholderArray = @[@"请输入对方的真实姓名（最多10位）",@"请输入对方与你的关系",@"请输入对方的昵称/详细关系（最多6位）"];
    NSArray * optionPlaceholderFirstArray = @[@"请输入性别",@"请输入生日"];
    NSArray * optionPlaceholderSecondArray = @[@"请输入对方的手机号码",@"请输入对方身份证"];
    /**
     *  把必填内容标题和提示存入字典，把标题和参数存入tempDic
     */
    for (NSInteger i = 0; i <requiredRemiderArray.count ; i++) {
        [self.placeholderDic setValue:requiredPlaceholderArray[i] forKey:requiredRemiderArray[i]];
        [self.tempDic setValue:requiredKeys[i] forKey:requiredRemiderArray[i]];
    }
    /**
     *  把选填内容标题和提示存入参数字典，把标题和参数存入tempDic
     *  提示字典 = 提示 : placeholder
     *  tempDic = 提示 : keys
     */
    for (NSInteger i = 0; i < optionRemindFirstArray.count; i++) {
        [self.placeholderDic setValue:optionPlaceholderSecondArray[i] forKey:optionReminderSecondArray[i]];
        [self.tempDic setValue:optionSecondkeys[i] forKey:optionReminderSecondArray[i]];
        [self.placeholderDic setValue:optionPlaceholderFirstArray[i] forKey:optionRemindFirstArray[i]];
        [self.tempDic setValue:optionRemindFirstKeys[i] forKey:optionRemindFirstArray[i]];
    }
}
#pragma mark - 创建tableView
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.tableView setSeparatorColor:CellLineColor];
    [self.view addSubview:self.tableView];

    
    /**
     *  把“我自己”的View添加作为table的headerview
     */
    self.headerView = [[[NSBundle mainBundle]loadNibNamed:@"AddFamilyHeaderView" owner:self options:nil] firstObject];
    if (IPhone6Plus) {
        self.headerView = [[[NSBundle mainBundle]loadNibNamed:@"AddFamilyHeaderView" owner:self options:nil] lastObject];
    }
    
    self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 74);
    if (IPhone6Plus) {
        self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 90);
    }
    self.headerView.topLineView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.headerView.familyHeadImgView setImage:[UIImage imageNamed:@"默认头像.png"]];
    self.headerView.familyHeadImgView.clipsToBounds = YES;
    self.headerView.familyHeadImgView.layer.cornerRadius = 3;
    [self.headerView.headerJumpImgView setImage:[UIImage imageNamed:@"公用_跳转.png"]];
    self.headerView.headerJumpImgView.right = kScreenWidth - 15;
    self.headerView.reminderLable.right = self.headerView.headerJumpImgView.left;

    self.headerView.headerTopLineView.backgroundColor = CellLineColor;
    self.headerView.topLineView.width = kScreenWidth;
    self.headerView.headerTopLineView.frame = CGRectMake(0, 9.5, kScreenWidth, 0.5);
    if (IPhone6Plus) {
         self.headerView.headerTopLineView.frame = CGRectMake(0, 11.5, kScreenWidth, 0.5);
        self.headerView.headerJumpImgView.right = kScreenWidth-20;
        self.headerView.reminderLable.right = self.headerView.headerJumpImgView.left-5;
    }
    self.headerView.headerBottomLineView.backgroundColor = CellLineColor;
    self.headerView.headerBottomLineView.frame = CGRectMake(0,self.headerView.height-0.5, kScreenWidth, 0.5);
        //点击上传家人头像
    [self.headerView.changHeadBtn addTarget:self action:@selector(changeHeaderImgView) forControlEvents:UIControlEventTouchUpInside];
    self.headerView.changHeadBtn.width = kScreenWidth;
    self.tableView.tableHeaderView = self.headerView;
}

#pragma mark - "出生年月"选择器
-(void)makeBirthdayPickerView
{
    
    self.myDatePickerView = [[MyDatePickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216)];
    [self.view addSubview:self.myDatePickerView];

    [self.myDatePickerView.cancleButton addTarget:self action:@selector(birthDateButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.myDatePickerView.cancleButton.tag = 1000;
    [self.myDatePickerView.sureButton addTarget:self action:@selector(birthDateButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.myDatePickerView.sureButton.tag = 1001;
    
}

/**
 *  取消  确定  按钮触发的事件
 *
 *  @param button 按钮的tag值1000是“取消”，1001是“确定”
 */
-(void)birthDateButtonClicked:(UIButton*)button
{
    switch (button.tag) {
        case 1000:
        {
            [self recoverPickerViewAndTableViewFrame];
        }
            break;
        case 1001:
        {
            self.selectedCell.getInformationLable.text = [self.myDatePickerView getDateString];
            [self.paratorDic setValue:[self.myDatePickerView getDateString] forKey:self.tempDic[self.selectedCell.familyReminderLable.text]];
            [self recoverPickerViewAndTableViewFrame];
        }
            break;
            
        default:
            break;
    }
    
    
}
#pragma mark - "关系"选择器
-(void)makeRelationShipPickerView
{
    self.relationShipArray = @[@"祖父母", @"父母",@"其他平辈", @"子女", @"孙辈",@"爱人"];
    self.relationShipView = [[[NSBundle mainBundle] loadNibNamed:@"FamilyRelationshipPickerView" owner:self options:nil] lastObject];
    self.relationShipView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 216);
    self.relationShipView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.relationShipView];
    /**
     *  pickerView--关系选择器
     */
    self.relationShipView.relationPickerView.delegate = self;
    self.relationShipView.relationPickerView.dataSource = self;
    self.relationShipView.relationPickerView.backgroundColor = [UIColor whiteColor];
    self.relationShipView.relationPickerView.showsSelectionIndicator=YES;
    /**
     *  初始选择第3行--“其他平辈”
     */
     [self.relationShipView.relationPickerView selectRow:3 inComponent:0 animated:NO];
    /**
     *  把初始选择的“其他平辈”参数值 4
     */
    self.relationShipString = [NSString stringWithFormat:@"%d",3+1];
    //“取消”--“确定”
    [self.relationShipView.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    self.relationShipView.cancleButton.tag = 2000;
    [self.relationShipView.cancleButton addTarget:self action:@selector(relationShipButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.relationShipView.sureButton setTitle:@"确定" forState:UIControlStateNormal];
    self.relationShipView.sureButton.tag = 2001;
    [self.relationShipView.sureButton addTarget:self action:@selector(relationShipButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
/**
 *  关系选择器“取消”，“确定” 按钮的触发事件//
 *
 *  @param button 按钮tag值2000是“取消”，2001是“确定”
 */
-(void)relationShipButtonClicked:(UIButton*)button
{
    /**
     *  取消按钮
     */
    if (button.tag == 2000) {
        [self recoverPickerViewAndTableViewFrame];
    }
    /**
     *  确定按钮
     */
    if (button.tag == 2001) {
        
        MyNSLog("self.relationShipArray.count %ld",self.relationShipArray.count);
        MyNSLog("%d",[self.relationShipString intValue]);
        self.selectedCell.getInformationLable.text = [self.relationShipArray objectAtIndex:[self.relationShipString intValue]-1];
        [self.paratorDic setValue:self.relationShipString forKey:@"type"];
        [self recoverPickerViewAndTableViewFrame];
    }
    

}
#pragma mark - pickerView的代理方法
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if ([pickerView isEqual:self.relationShipView.relationPickerView]) {
        return 1;
    }
    else
    {
        return 0;
    }
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([pickerView isEqual:self.relationShipView.relationPickerView]) {
        return self.relationShipArray.count;
    }else
    {
        return 0;
    }
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([pickerView isEqual:self.relationShipView.relationPickerView]) {
        return self.relationShipArray[row];
    }else
    {
        return nil;
    }
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == self.relationShipView.relationPickerView) {
        self.relationShipString = [NSString stringWithFormat:@"%ld",row+1];
       MyNSLog("%@",self.relationShipString);
    }
    
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    if (pickerView == self.relationShipView.relationPickerView) {
        return 40;
    }else
    {
        return 0;
    }
}
#pragma mark - table的代理方法
//多少段
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.takeDrugDataArray.count;
}
//每段有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.takeDrugDataArray[section] count];
}
//段头视图
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    CGFloat viewLeft = 15;
    CGFloat viewHeight = 20;
    CGFloat textFont = 13;
    if (IPhone6Plus) {
        viewHeight = 30;
        viewLeft = 20;
        textFont = 15;
    
    }
    
    //必填内容
    if (section == 0) {
        self.requiredSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, viewHeight)];
        self.requiredSectionHeaderView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        UILabel *requiredLable = [[UILabel alloc] initWithFrame:CGRectMake(viewLeft, 0, 100, viewHeight)];
        requiredLable.text = @"必填内容";
        requiredLable.textAlignment = NSTextAlignmentLeft;
        requiredLable.font = [UIFont systemFontOfSize:textFont];
        requiredLable.textColor = [UIColor grayColor];
        [self.requiredSectionHeaderView addSubview:requiredLable];
        
        return self.requiredSectionHeaderView;
    }
    //选填内容
    else if (section == 1)
    {
        self.optionSectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, viewHeight)];
        self.optionSectionHeaderView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        UILabel *optionLable = [[UILabel alloc] initWithFrame:CGRectMake(viewLeft, 0, 100, viewHeight)];
        optionLable.text = @"选填内容";
        optionLable.textAlignment = NSTextAlignmentLeft;
        optionLable.font = [UIFont systemFontOfSize:textFont];
        optionLable.textColor = [UIColor grayColor];
        [self.optionSectionHeaderView addSubview:optionLable];
        
        return self.optionSectionHeaderView;
        
    }else
    {
        return nil;
    }
}
//段头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2) {
        return 0.01;
    }else
    {
        if (IPhone6Plus) {
            return 30;
        }else{
            return 20;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (IPhone6Plus) {
        return 53;
    }else{
        return 44;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

#pragma mark ---加载Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddFamilyRemindCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        if (IPhone6Plus) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddFamilyRemindCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"AddFamilyRemindCell" owner:self options:nil] firstObject];
        }
    }
    [cell.jumpImgView setImage:[UIImage imageNamed:@"公用_跳转.png"]];
    cell.jumpImgView.right = kScreenWidth-15;
    if (IPhone6Plus) {
        cell.jumpImgView.right = kScreenWidth-20;
    }
    
    cell.getInformationLable.frame = CGRectMake(cell.familyReminderLable.right+10, cell.getInformationLable.top, cell.jumpImgView.left -cell.familyReminderLable.right-10 - 5  , cell.getInformationLable.height);
    
    //第1段--必填内容
    if (indexPath.section == 0)
    {
        //信息提示lable
        cell.familyReminderLable.text = self.takeDrugDataArray[indexPath.section][indexPath.row];
        if (indexPath.row == 0 ) {
            cell.topLineView.backgroundColor = CellLineColor;
            cell.topLineView.height = 0.35;
            cell.topLineView.width = kScreenWidth;
        }
        if (indexPath.row == 2) {
            cell.bottomLineView.backgroundColor = CellLineColor;
            
            cell.bottomLineView.frame = CGRectMake(0, cell.height-0.5, kScreenWidth, 0.5);
        }
        
    }
    else//选填内容
    {
        //信息提示lable
        cell.familyReminderLable.text = self.takeDrugDataArray[indexPath.section][indexPath.row];
        if (indexPath.section == 1 && indexPath.row == 0) {
            cell.topLineView.backgroundColor = CellLineColor;
            cell.topLineView.height = 0.3;
            cell.topLineView.width = kScreenWidth;
        }
        if (indexPath.section == 2 && indexPath.row == 0) {
            cell.topLineView.backgroundColor = CellLineColor;
            
            cell.topLineView.frame = CGRectMake(15, 0, kScreenWidth-15, 0.3);
            if (IPhone6Plus) {
                cell.topLineView.left = 20;
            }
        }
        if (indexPath.section == 2 && indexPath.row == 1) {
            cell.bottomLineView.backgroundColor = CellLineColor;
            cell.bottomLineView.frame = CGRectMake(0, cell.height, kScreenWidth, 0.35);
        }
   
    }
    
    return cell;
}

#pragma mark - 选中某一行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /**
     *  当点击某一行的时候 让 “关系”“年月”pickerView 下去
     */
    /**
     *  选中某一个cell，就让全局的selectedCell指向这个cell
     */
    self.selectedCell = (AddFamilyRemindCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    //切割字符串--把空格切割掉
     NSArray * titleArray  = [self.selectedCell.familyReminderLable.text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
    /**
     *  切割完成后的字符串
     */
    NSMutableString *titleString = [NSMutableString stringWithCapacity:0];
    for (NSString *str in titleArray) {
        [titleString appendString:str];
    }
    //点击--关系
    if ([titleString isEqualToString:@"关系"])
    {
        [self scrollToRowAtLastSecionWithLastIndexPath];
        [self makeAlphaView];
        [self.view bringSubviewToFront:self.relationShipView];
         //点击“关系”弹出 关系选择器pickerview
        [UIView animateWithDuration:0.35 animations:^{
            self.relationShipView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin-216, kScreenWidth, 216);
            self.alphaView.alpha = 0.35;
        } completion:^(BOOL finished) {
            
        }];

    }
    //点击--性别
    else if ([titleString isEqualToString:@"性别"])
    {
        if ([self.paratorDic[@"gender"] intValue] == 1|| [self.paratorDic[@"gender"] intValue] == 2 ) {
            return;
        }else{
            [self addSexActionSheet];
        }
    }
    //点击--“出生年月”
    else if ([titleString isEqualToString:@"出生年月"])
    {
        //滑动table使最后一个cell漏出来
        [self scrollToRowAtLastSecionWithLastIndexPath];
         [self makeAlphaView];
        [self.view bringSubviewToFront:self.myDatePickerView];
        //点击“出生年月”让年月选择器上来
        [UIView animateWithDuration:0.35 animations:^{
           
            self.myDatePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin-216, kScreenWidth, 216);
            //iphone4\4s
            if (kScreenHeight == 480) {
                //把table也向上移动，是该cell并不被覆盖
                self.tableView.frame = CGRectMake(0, -128, kScreenWidth, kScreenHeight-iOS7TopMargin);
            }
            //iphone5
            if (kScreenHeight == 568) {
                self.tableView.frame = CGRectMake(0, -45, kScreenWidth, kScreenHeight-iOS7TopMargin);
            }
            
            self.alphaView.alpha = 0.35;
        } completion:^(BOOL finished) {
            
        }];
        
  
    }
    //点击--其他行
    else
    {
        if (indexPath.section == 2) {
            [self scrollToRowAtLastSecionWithLastIndexPath];
        }
        WriteFamilyViewController *write = [[WriteFamilyViewController alloc] init];
        write.textFieldPlaceholder = [self.placeholderDic objectForKey:self.selectedCell.familyReminderLable.text];
        write.delegate = self;
        write.navBarTitle = titleString;
        write.textString = self.selectedCell.getInformationLable.text;
        [self.navigationController pushViewController:write animated:YES];
    }
    
}
#pragma mark - WriteFamilyViewControllerDelegate的代理方法
/**
 *  把参数placeholder赋值给选中的cell的对应lable。并且把这个信息存入参数字典
 *  @param placeholder 添加的信息
 */
-(void)reloadTableViewSelectedCellPlaceholeder:(NSString *)placeholder
{
    self.selectedCell.getInformationLable.text = placeholder;
    //把传过来的值存入参数字典
    [self.paratorDic setValue:placeholder forKey:self.tempDic[self.selectedCell.familyReminderLable.text]];
}
/**
 *  点击头像
 */
#pragma mark - 触发--添加头像
-(void)changeHeaderImgView
{
    MyNSLog("点击上传家人头像");
    //让“关系”"出生年月" - pickerView下去
    [self recoverPickerViewAndTableViewFrame];
    
    self.headerActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"图片库", nil];
    [self.headerActionSheet showInView: [[UIApplication sharedApplication].delegate window]];
    
}
#pragma mark - 触发选择性别
-(void)addSexActionSheet{
    self.sexActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate: self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
    [self.sexActionSheet showInView: [[UIApplication sharedApplication].delegate window]];
}
#pragma mark - -ActionSheet的代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    //点击的是--》性别 提醒
    if (actionSheet == self.sexActionSheet) {
        if (buttonIndex != 2) {
            self.actionSheetButtonIndex = buttonIndex;
            UIAlertView *sexAlertView = [[UIAlertView alloc] initWithTitle:@"性别选取" message:@"确定后不可修改" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            sexAlertView.tag = 1990;
            [sexAlertView show];
        }
    }
    
    //点击的是--》头像图片选取方式提醒
    if (actionSheet == self.headerActionSheet) {
        //照相机
        if (buttonIndex == 0)
        {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus != AVAuthorizationStatusAuthorized)
            {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"相机被禁用" message:@"请在iPhone的“设置-隐私-相机”中允许安好访问您的相机。" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
            else
            {
                
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                    pickerImage.delegate=self;
                    pickerImage.allowsEditing=YES;
                    //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
                    pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
                    [self presentViewController:pickerImage animated:YES completion:nil];
                }else{
                    
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }
            
        }
        //图片库
        else if (buttonIndex == 1)
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                pickerImage.delegate=self;
                NSArray * array1=[NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
                pickerImage.mediaTypes=array1;
                pickerImage.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.allowsEditing=YES;
                [self presentViewController:pickerImage animated:YES completion:nil];
            }
            else
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
        }
    }

}
#pragma mark - alert提醒
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //点击性别ActionSheet弹出选好“男”/“女”之后，弹出这个alertView提醒--告知选好性别不可修改
    if (alertView.tag == 1990)
    {
        if (buttonIndex == 1) {
            if (self.actionSheetButtonIndex == 0) {
                self.selectedCell.getInformationLable.text = @"男";
                [self.paratorDic setValue:@"1" forKey:@"gender"];
            }else if (self.actionSheetButtonIndex == 1){
                self.selectedCell.getInformationLable.text = @"女";
                [self.paratorDic setValue:@"2" forKey:@"gender"];
            }
        }
    }
    
}


#pragma mark - 获取头像的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:^{
        self.familyHeaderImg = image;
        [self.headerView.familyHeadImgView setImage:self.familyHeaderImg];

    }];
}

#pragma mark - pickerView下落，tableview复原
/**
 *  让pickerView和tableview的位置恢复原状
 */
-(void)recoverPickerViewAndTableViewFrame
{
    [UIView animateWithDuration:0.35 animations:^{
        self.relationShipView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.myDatePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin);
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
    }];
    
}
#pragma mark - 让tableview的最后一行cell显示出来
-(void)scrollToRowAtLastSecionWithLastIndexPath
{
    //找到最后一个cell
    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];//制定第2段的坐标为1的cell->indexPath
    //让屏幕上滑到指定的一个cell完全显示出来
    [self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
#pragma mark - 创建半透明的view
-(void)makeAlphaView
{
    self.alphaView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    self.alphaView.backgroundColor = [UIColor blackColor];
    self.alphaView.alpha = 0;
    [self.view addSubview:self.alphaView];
    //给这个半透明的View添加一个手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewTapClicked:)];
    [self.alphaView addGestureRecognizer:tap];
}
-(void)alphaViewTapClicked:(UITapGestureRecognizer*)tap{

    [self recoverPickerViewAndTableViewFrame];
    

}

@end
